#pragma once
#include <iostream>
#include <string>
#include <filesystem> //C++17
#include <fstream>
#include <unordered_map>
#include "Log.hpp"
#include "Mutex.hpp"
using namespace LogModule;
const std::string default_dict_path = "../dict.txt";
const std::string sep = ": ";
class Dict
{

public:
    Dict(const std::string &path = default_dict_path) : _path(path) {}
    std::string Translate(const std::string &key)
    {
        // auto it = _dict.find(key);
        // if (it != _dict.end())
        // {
        //     return it->second;
        // }
        LOG(LogLevel::DEBUG) << "Translate:";
        auto it = _dict.find(key);
        if (it == _dict.end())
        {
            return "未找到该单词";
        }
        return it->second;
    }
    bool Load(const std::string &path = default_dict_path)
    {
        // _path = path;
        // if (!std::filesystem::exists(_path))
        // {
        //     std::cerr << "file is not exist" << std::endl;
        // }
        std::ifstream in(_path);
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file failed";
            return false;
        }
        std::string line;
        while (std::getline(in, line))
        {
            // apple: 苹果
            auto pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "bad line:" << line;
                continue;
            }
            std::string key = line.substr(0, pos);
            std::string value = line.substr(pos + sep.size());
            if (key.empty() || value.empty())
            {
                LOG(LogLevel::WARNING) << "bad line:" << line;
                continue;
            }
            _dict.insert(std::make_pair(key, value));
            LOG(LogLevel::INFO) << "Load:" << key << "->" << value;
        }

        in.close();
        LOG(LogLevel::INFO) << "Load dict file success";

        return true;
    }
    ~Dict()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _path; // 文件路径
};
